package com.cardone.common.security.shiro.authc.credential;

import com.cardone.common.util.TextEncryptorUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;

/**
 * Created by c1000000001 on 14-12-28.
 */
public class TextEncryptorCredentialsMatcher implements CredentialsMatcher {
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;

        SimpleAuthenticationInfo authenticationInfo = (SimpleAuthenticationInfo) info;

        String tokenPassword = new String(usernamePasswordToken.getPassword());
        String infoPassword = authenticationInfo.getCredentials().toString();

        if (authenticationInfo.getCredentialsSalt() != null) {
            String salt = authenticationInfo.getCredentialsSalt().toHex();

            String oldDecryptPassword = TextEncryptorUtils.decrypt(salt, infoPassword);

            return StringUtils.equals(oldDecryptPassword, tokenPassword);
        }

        String encryptPassword = DigestUtils.md5Hex(tokenPassword);

        return StringUtils.equals(encryptPassword, infoPassword);
    }
}
